package com.chagee.store.operation.server.hadler;

import com.alibaba.fastjson.JSON;
import com.chagee.base.exception.BaseException;
import com.chagee.base.utils.SoaResponse;
import com.chagee.base.utils.SoaUtil;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author bwcj_zx
 */
@Component
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class ExceptionHandlerAop {
	@Around("execution(* com.chagee.store.operation.server.facade.provider..*.*(..))")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		try {
			return joinPoint.proceed();
		} catch (BizException e) {
			log.error("ExceptionHandlerAop:", e);
			return buildResponse(e);
		} catch (BaseException e) {
			log.error("ExceptionHandlerAop_BaseException:", e);
			return buildResponse(e.getErrorCode(), e.getErrorMsg(), null);
		} catch (Exception e) {
			log.error("ExceptionHandlerAop_Exception", e);
			return buildResponse(BizErrorCode.FAIL.getErrorCode(), BizErrorCode.FAIL.getErrorMsg(), JSON.toJSONString(e));
		}
	}

	private Object buildResponse(String code, String errMsg, String innerMsg) {
		return SoaUtil.error(code, errMsg, innerMsg);
	}

	/**
	 * 全局异常处理
	 *
	 * @param e
	 * @return
	 */
	private SoaResponse<?, ?> buildResponse(BizException e) {
		return SoaUtil.error(e.getErrorCode(), e.getErrorMsg(), null);
	}
}
